//
//  CodeExample.m
//  LSCodeLibrary
//
//  Created by Samuel on 15/4/1.
//  Copyright (c) 2015年 Samuel. All rights reserved.
//

#import "CodeExample.h"
#import <objc/runtime.h>
#import <CommonCrypto/CommonDigest.h>
@interface CodeExample ()

@end
/*------------------------------------------------------------------------------------*/
@implementation ShareObject

#pragma mark 单例创建
+ (instancetype)ShareSingleton
{
    static ShareObject *Singleton=nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Singleton=[[ShareObject alloc] init];
    });
    return Singleton;
}
@end


/*------------------------------------------------------------------------------------*/


@implementation CodeExample
#pragma mark 复写init方法
-(instancetype)init{
    self=[super init];
    if (self) {
        ;
    }
    return self;
}

#pragma mark 遍历UITableViewCell
+ (NSIndexPath *)SubView:(UIView *)subview TableView:(UITableView *)tableView{
    while (![subview isKindOfClass:[UITableViewCell class]]) {
        subview=subview.superview;
    }
    NSIndexPath * path = [tableView indexPathForCell:(UITableViewCell *)subview];
    return path;
}
@end
/*------------------------------------------------------------------------------------*/
@implementation NSString (Hash)

-(NSString*)MD5String{
    NSData *data=[self dataUsingEncoding:NSUTF8StringEncoding];
    unsigned char md[CC_MD5_DIGEST_LENGTH];
    memset(md, 0, sizeof(md));
    CC_MD5([data bytes], (CC_LONG)[data length], md);
    NSData *digest=[NSData dataWithBytes:md length:sizeof(md)];
    const unsigned char *dataBuffer=(const unsigned char *)[digest bytes];
    if (!dataBuffer){
        return nil;
    }
    NSUInteger dataLength=[digest length];
    NSMutableString *hex=[NSMutableString stringWithCapacity:(dataLength * 2)];
    for (int i = 0; i < dataLength; ++i){
        [hex appendString:[NSString stringWithFormat:@"%02x", (unsigned int)dataBuffer[i]]];
    }
    return hex;
}

-(NSString*)urlencode{
    CFStringRef string=CFURLCreateStringByAddingPercentEscapes( kCFAllocatorDefault, (CFStringRef)self, CFSTR(""), CFSTR(""), kCFStringEncodingUTF8);
    NSString *encodedString = CFBridgingRelease(string);
    return encodedString;
}

-(id)JSONObject{
    NSData *data=[self dataUsingEncoding:NSUTF8StringEncoding];
    return [data JSONObject];
}

-(NSString*)resourcePath{
    return [[NSBundle mainBundle] pathForResource:self ofType:nil];
}
-(NSData*)readData{
    return [NSData dataWithContentsOfFile:self];
}

-(NSString*)readString{
    NSData *data=[NSData dataWithContentsOfFile:self];
    return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}

@end
/*------------------------------------------------------------------------------------*/
@implementation UIView (BarButtonItem)

-(UIBarButtonItem*)barButtonItem{
    if ([self isKindOfClass:[UIButton class]]) {
        UIButton *button=(id)self;
        UIColor *blue=[UIColor colorWithRed:0.0/255 green:122.0/255 blue:255.0/255 alpha:1.0];
        [button setTitleColor:blue forState:UIControlStateNormal];
    }
    return [[UIBarButtonItem alloc] initWithCustomView:self];
}
-(void)removeAllSubviews{
    //    MBLog(@"这是谁  %@",self);
    while (self.subviews.count>0) {
        UIView *subview=self.subviews.firstObject;
        [subview removeFromSuperview];
    }
}

static const char* activity="task.activity.indicator";
-(void)runTask:(dispatch_block_t)block{
    UIActivityIndicatorView *indicator=objc_getAssociatedObject(self, &activity);
    if (!indicator) {
        indicator=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        objc_setAssociatedObject(self, &activity, indicator, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        [self addSubview:indicator];
    }
    indicator.center=CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds));
    [indicator startAnimating];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        if (block) {
            block();
        }
        [indicator stopAnimating];
    });
}

+(void)load{
    UIColor *blue=[UIColor colorWithRed:0.0/255 green:122.0/255 blue:255.0/255 alpha:1.0];
    [[UIButton appearance] setTitleColor:blue forState:UIControlStateNormal];
}

@end
/*------------------------------------------------------------------------------------*/
@implementation UIButton (ImageButton)

+(instancetype)buttonWithImage:(NSString*)imageStr{
    UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];
    UIImage *image=[UIImage imageNamed:imageStr];
    [button setImage:image forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@S",imageStr]] forState:UIControlStateHighlighted];
    [button setFrame:CGRectMake(0, 0, 40, 40)];
    return button;
}

@end
/*------------------------------------------------------------------------------------*/
@implementation UIImageView (WebImage)

-(NSString*)filePathForImageURL:(NSString*)urlstring{
    NSString *md5=[urlstring MD5String];
    NSString *cache=NSTemporaryDirectory();
    NSString *filepath=[cache stringByAppendingPathComponent:@"caches"];
    if (![[NSFileManager defaultManager] fileExistsAtPath:filepath]) {
        NSError *error=nil;
        [[NSFileManager defaultManager] createDirectoryAtPath:filepath withIntermediateDirectories:YES attributes:nil error:&error];
    }
    return [filepath stringByAppendingPathComponent:md5];
}

static const char* download="image.download.queue";
-(NSString*)getImageURL{
    NSString *requested=objc_getAssociatedObject(self, &download);
    return requested;
}
-(void)setImageURL:(NSString*)urlstring{
    if (self.image) {
        NSString *requested=[self getImageURL];
        if ([requested isEqualToString:urlstring]) {
            return;
        }
    }
    NSString *filepath=[self filePathForImageURL:urlstring];
    //    MBLog(@"%f  %f %f",self.frame.size.width,self.frame.size.height,MAX(self.frame.size.width, self.frame.size.height));
    if (self.frame.size.height==450)
    {
        filepath=[filepath stringByAppendingPathExtension:@"thumbnail450"];
    }else
        if (MAX(self.frame.size.width, self.frame.size.height)<=40)
        {
            filepath=[filepath stringByAppendingPathExtension:@"thumbnail40"];
        }else
            if (MAX(self.frame.size.width, self.frame.size.height)<=100)
            {
                filepath=[filepath stringByAppendingPathExtension:@"thumbnail100"];
            }else
                if (MAX(self.frame.size.width, self.frame.size.height)<=320) {
                    filepath=[filepath stringByAppendingPathExtension:@"thumbnail320"];
                }else if (MAX(self.frame.size.width, self.frame.size.height)<=360) {
                    filepath=[filepath stringByAppendingPathExtension:@"thumbnail360"];
                }
    if ([[NSFileManager defaultManager] fileExistsAtPath:filepath]) {
        NSError *error=nil;
        NSData *data=[NSData dataWithContentsOfFile:filepath options:NSDataReadingMappedIfSafe error:&error];
        if (!error) {
            UIImage *image=[UIImage imageWithData:data];
            if (image) {
                self.image=image;
            }
        }
    }
    if (!self.image) {
        [self fetchImageFromURL:urlstring];
    }
    objc_setAssociatedObject(self, &download, urlstring, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
-(void)fetchImageFromURL:(NSString*)urlstring{
    NSString *requested=[self getImageURL];
    if ([requested isEqualToString:urlstring]) {
        return;
    }
    UIActivityIndicatorView *activity=(id)[self viewWithTag:1234];
    if (!activity) {
        activity=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        activity.tag=1234;
        [self addSubview:activity];
    }
    activity.center=CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds));
    [activity startAnimating];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        @autoreleasepool {
            NSURL *url=[NSURL URLWithString:urlstring];
            NSError *error=nil;
            NSData *data=[NSData dataWithContentsOfURL:url options:NSDataReadingMappedIfSafe error:&error];
            if (!error) {
                UIImage *image=[UIImage imageWithData:data];
                if (image) {
                    NSString *filepath = nil;
                    if (image.size.height==450)
                    {
                        //image=[UIImageView generateThumbnail:image];
                        filepath=[self filePathForImageURL:urlstring];
                        filepath=[filepath stringByAppendingPathExtension:@"thumbnail450"];
                        data=UIImageJPEGRepresentation(image, 0.5);
                        [data writeToFile:filepath atomically:YES];
                    }else
                        if (MAX(image.size.width, image.size.height)<=40)
                        {
                            //image=[UIImageView generateThumbnail:image];
                            filepath=[self filePathForImageURL:urlstring];
                            filepath=[filepath stringByAppendingPathExtension:@"thumbnail40"];
                            data=UIImageJPEGRepresentation(image, 0.5);
                            [data writeToFile:filepath atomically:YES];
                        }else
                            if (MAX(image.size.width, image.size.height)<=100)
                            {
                                //image=[UIImageView generateThumbnail:image];
                                filepath=[self filePathForImageURL:urlstring];
                                filepath=[filepath stringByAppendingPathExtension:@"thumbnail100"];
                                data=UIImageJPEGRepresentation(image, 0.5);
                                [data writeToFile:filepath atomically:YES];
                            }else
                                if (MAX(image.size.width, image.size.height)<=320)
                                {
                                    //image=[UIImageView generateThumbnail:image];
                                    filepath=[self filePathForImageURL:urlstring];
                                    filepath=[filepath stringByAppendingPathExtension:@"thumbnail320"];
                                    //data=UIImageJPEGRepresentation(image, 0.5);
                                    [data writeToFile:filepath atomically:YES];
                                }else if (MAX(image.size.width, image.size.height)<=360)
                                {
                                    //image=[UIImageView generateThumbnail:image];
                                    filepath=[self filePathForImageURL:urlstring];
                                    filepath=[filepath stringByAppendingPathExtension:@"thumbnail360"];
                                    data=UIImageJPEGRepresentation(image, 0.6);
                                    [data writeToFile:filepath atomically:YES];
                                }else
                                {
                                    filepath=[self filePathForImageURL:urlstring];
                                    [data writeToFile:filepath atomically:YES];
                                }
                    
                    
                    NSString *imageurl=[self getImageURL];
                    if ([imageurl isEqualToString:urlstring]) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [activity stopAnimating];
                            [self setImageURL:urlstring];
                        });
                    }
                }
            }
            else{
                NSLog(@"%@",error);
            }
        }
    });
}

+(UIImage *)generateThumbnail:(UIImage *)image{
    CGFloat scaleX=350/image.size.width;
    CGFloat scaleY=350/image.size.height;
    CGFloat scale=MAX(scaleX, scaleY);
    int width=image.size.width*scale;
    int height=image.size.height*scale;
    UIGraphicsBeginImageContext(CGSizeMake(width, height));
    [image drawInRect:CGRectMake(0, 0, width, height)];
    UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return result;
}

@end
/*------------------------------------------------------------------------------------*/
@implementation NibLoader

+(UIView*)loadNib:(NSString *)nibName{
    return [NibLoader loadNib:nibName bundle:nil];
}

+(UIView*)loadNib:(NSString*)nibName bundle:bundle{
    NibLoader *loader=[[NibLoader alloc] init];
    UINib *nib=[UINib nibWithNibName:nibName bundle:bundle];
    [nib instantiateWithOwner:loader options:nil];
    return loader.nibView;
}

@end
/*------------------------------------------------------------------------------------*/
@implementation WebService

+(instancetype)serviceWithApi:(NSDictionary*)api{
    WebService *service=[[WebService alloc] init];
    [service setApi:api];
    return service;
}
-(void)setApi:(NSDictionary*)api{
    NSLog(@"%@",api);
}
-(void)execute{
    
}

@end
/*------------------------------------------------------------------------------------*/
@implementation NSArray (List)

-(BOOL)containsString:(NSString*)string{
    for (id obj in self) {
        if ([obj isKindOfClass:[NSString class]]) {
            NSString *value=obj;
            if ([value isEqualToString:string]) {
                return YES;
            }
        }
    }
    return NO;
}

-(NSArray*)arrayByRemoveNullValue{
    NSMutableArray *array=[NSMutableArray array];
    for (id obj in self) {
        if (![obj isKindOfClass:[NSNull class]]) {
            [array addObject:obj];
        }
    }
    return array;
}

-(NSString*)JSONString{
    NSData *data=nil;
    NSError *error=nil;
    data=[NSJSONSerialization dataWithJSONObject:self options:0 error:&error];
    NSString *string=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    return string;
}

@end
/*------------------------------------------------------------------------------------*/
@implementation NSDictionary (List)

-(NSDictionary*)dictionaryByRemoveNullValue{
    NSMutableDictionary *dictionary=[NSMutableDictionary dictionary];
    [self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        if (![obj isKindOfClass:[NSNull class]]) {
            [dictionary setValue:obj forKey:key];
        }
    }];
    return dictionary;
}

-(NSString*)JSONString{
    NSData *data=nil;
    NSError *error=nil;
    data=[NSJSONSerialization dataWithJSONObject:self options:0 error:&error];
    NSString *string=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    return string;
}

@end
/*------------------------------------------------------------------------------------*/
@implementation NSObject (Payload)

static const char* payload="nsobject.payload";
-(id)payloadObject{
    return objc_getAssociatedObject(self, &payload);
}
-(void)setPayloadObject:(id)payloadObject{
    objc_setAssociatedObject(self, &payload, payloadObject, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end
/*------------------------------------------------------------------------------------*/
@implementation NSData (JSON)

-(id)JSONObject{
    id object=nil;
    NSError *error=nil;
    object=[NSJSONSerialization JSONObjectWithData:self options:NSJSONReadingMutableContainers error:&error];
    return object;
}

@end

